package com.bj58.ecdata.mailreport.dao;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bj58.sfft.utility.dao.basedao.DAOHelper;
import com.bj58.sfft.utility.dao.basedao.IDAO;

public class DBUtils {
	private static final Log log = LogFactory.getLog(DBUtils.class);
	
	private static  Map<String, DAOHelper> daoCache = new ConcurrentHashMap<String, DAOHelper>();

	/**
	 * 根据配置文件位置获取dao--有缓存
	 * @param config
	 * @return
	 * @author zhaoxiang 20150202
	 */
	public static IDAO getDao(String config) {
		DAOHelper helper = getDAOHelper(config);
		if (helper != null) {
			return helper.sql;
		}
		return null;
	}

	/**
	 * 根据配置文件位置获取daohelper实例--有缓存
	 * @param config
	 * @return
	 * @author zhaoxiang 20150202
	 */
	public static DAOHelper getDAOHelper(String config) {
		if (StringUtils.isBlank(config)) {
			return null;
		}
		DAOHelper dao = daoCache.get(config.trim());
		if (dao == null) {
			synchronized (daoCache) {
				dao = daoCache.get(config.trim());
				if(dao == null){
					dao = get(config.trim());
					if (dao != null) {
						daoCache.put(config.trim(), dao);
					}
				}
			}
		}
		return dao;
	}

	private static DAOHelper get(String config_path) {
		DAOHelper daoHelper = null;
		try {
			daoHelper = MyDAOBase.createIntrance(config_path);
			log.info("------------load db.properties success : " + config_path + "---------");
		} catch (Exception e) {
			log.info("数据库连接异常", e);
		}
		return daoHelper;
	}

}
